<?php
/**
 * AccountsController is for all accounts operation before signing in.
 * 
 * Bocheng Chen, 10.07.2012
 * 
 * LBB Solutions Oy 版权所有 @ 2012
 */
class LoginForm extends CFormModel
{
	public $user_input;//email, mobile or yamii code(ID)
	public $type_no; //0 - ID, 1 - Email, 2 - Mobile
	public $email;
	public $mobile;
	public $id;
	public $password;
	public $password_repeat;
	public $rememberMe;

	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			//email and password are required
			//array('email', 'email', 'allowEmpty'=>false, 'checkMX'=>false, 'message'=>BUtils::T('email_address_error_msg')),
			array('user_input, password', 'required', 'message'=>BUtils::T('cannot_be_blank_msg')),
			array('password', 'authenticate', 'on'=>'login'),// password needs to be authenticated on login
			array('password_repeat', 'required', 'on'=>'signup', 'message'=>BUtils::T('cannot_be_blank_msg')),
			array('password_repeat', 'compare', 'compareAttribute'=>'password', 'on'=>'signup'),
			// rememberMe needs to be a boolean
			array('rememberMe', 'boolean', 'on'=>'login'),
			array('user_input', 'authenticate', 'on'=>'signup'),
			
			// user_input needs to be authenticated on register
			array('user_input, password', 'authenticate', 'on'=>'register'),
			array('password_repeat', 'required', 'on'=>'register'),
			array('password_repeat', 'compare', 'compareAttribute'=>'password', 'on'=>'register'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'id' => BUtils::T('user_code_lbl'),
			'user_input' => BUtils::T('user_email_phone_number_lbl'),
			'password' => BUtils::T('password_lbl'),
			'password_repeat' => BUtils::T('password_repeat_lbl'),
			'rememberMe' => BUtils::T('remember_next_time_lbl'),
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute, $params) {
		if (!$this->hasErrors()) {
			//verify user_input
			$this->user_input = trim($this->user_input);
			$this->type_no = CustomerHelper::getType($this->user_input);
			//Important: For register, there is no user ID input
			if ($params['on'] !== 'login' and $this->type_no == 0) $this->type_no = 2;
			if (2 == $this->type_no) {
				try {
					$this->mobile = CustomerHelper::formatMobile($this->user_input);
					$this->user_input = $this->mobile;//format mobile number
				} catch (Exception $ex) {
					$this->addError('user_input', $ex->getMessage());
					return;
				}
			} elseif (1 == $this->type_no) {
				$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
				if (!preg_match($regex, $this->user_input)) {
					$this->addError('user_input', BUtils::T('email_address_error_msg'));
					return;
				} else {
					$this->email = $this->user_input;
				}
			} else {
				//only login with Yamii code (ID)
				$this->id = $this->user_input;
			}
			
			if ($params['on'] === 'login') {
				try {
					$this->_identity = new UserIdentity($this->user_input, $this->password);
					$this->_identity->setType($this->type_no);
					$this->_identity->authenticate();
				} catch (Exception $ex) {
					$this->addError('user_input', $ex->getMessage());
					return;
				}
				switch($this->_identity->errorCode) {
					case UserIdentity::ERROR_NONE:
						$duration = $this->rememberMe ? 3600*24*30 : 0; // 30 day
						Yii::app()->user->login($this->_identity, $duration);
						break;
					case UserIdentity::ERROR_USERNAME_INVALID:
						$this->addError('user_input', BUtils::T('user_not_exist_msg'));
						break;
					default:
						$this->addError('password', Yii::t('app','Password is incorrect!'));
						break;
				}
			} elseif ($params['on'] === 'signup') {
				//validate if input email or mobile exists
				$connection = Yii::app()->db;
				$command = $connection->createCommand('SELECT id FROM tbl_user_account WHERE email=:user OR mobile=:user');
				$row = $command->queryRow(true, array(':user' => $this->user_input));
				$connection->active = false;
				if (!empty($row)) {
					if (1 === $this->type_no) $message = BUtils::T('duplicate_email_error_msg');
					else $message = BUtils::T('user_phone_number_exist_msg');
					$this->addError('user_input', $message);
				}
			} else {
				//validate if input email or mobile exists with status=99
				$connection = Yii::app()->db;
				$command = $connection->createCommand('SELECT id, status FROM tbl_user_account WHERE email=:user OR mobile=:user');
				$row = $command->queryRow(true, array(':user' => $this->user_input));
				$connection->active = false;
				if (empty($row)) {
					if (1 === $this->type_no) $message = Yii::t('app', 'You have not yet use this email at store!');
					else $message = Yii::t('app', 'You have not yet use this phone number at store!');
					$this->addError('user_input', $message);
				} elseif ($row['status'] != 99) {
					if (1 === $this->type_no) $message = Yii::t('app', 'This email address has been registered!');
					else $message = Yii::t('app', 'This phone number has been registered!');
					$this->addError('user_input', $message);
				}
				
				//find the user with 99 status
				$this->id = $row['id'];
			}
		}
	}
	
	/**
	 * Signs up in the user using the given username and password in the model.
	 * @return boolean whether sign-up is successful
	 */
	public function signup() {
		if ($this->_identity === null) {
			$this->_identity = new UserIdentity($this->user_input, $this->password);
			$this->_identity->setType($this->type_no);
			$this->_identity->createAccount();
		}
		if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
			Yii::app()->user->login($this->_identity, 0);
			return true;
		} else {
			$this->addError('user_input', 'Error when create account! Please contact Yawii support.');
			return false;
		}
	}
	
	/**
	 * Register with mobile/email
	 * @return boolean whether register is successful
	 */
	public function register() {
		if ($this->_identity === null) {
			$this->_identity = new UserIdentity($this->user_input, $this->password);
			$this->_identity->setType($this->type_no);
			$this->_identity->registerAccount($this->id);
		}
		if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
			Yii::app()->user->login($this->_identity, 0);
			return true;
		} else {
			$this->addError('user_input', 'Error when create account! Please contact Yawii support.');
			return false;
		}
	}
}
